jQuery(document).ready(function() {	
	jQuery("#note").submit(function() {	
		// Perform your validation error checking here
		var formData = jQuery("#note").serialize();				
		jQuery.ajax({
			type: "POST",
			url: "docs/note/add",
			cache: false,
			data: formData,
			timeout: 3000,
			dataType: "json",			
			beforeSend: function() { 
			    ajaxBeforeSend(); 
			}, 
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				ajaxOnError(XMLHttpRequest, textStatus, errorThrown);
			},
			success: function(data) {
				ajaxOnSuccess(data);
			}
		});
		
		return false;	
	});	
});

function ajaxBeforeSend() {	
	jQuery("#messages").html('<img class="ajaxloadimg" src="public/spica/ajax-loader.gif" /><p class="save">Please wait, saving your note ...</p>');	
	jQuery("#note input[name=submit]").hide();		
	jQuery("#note input").attr("disabled", "disabled");	
	jQuery("#noteFeedback").hide();
	jQuery("#usernameFeedback").hide();
	jQuery("#pageIDFeedback").hide();
}

function ajaxOnError(XMLHttpRequest, textStatus, errorThrown) {
	jQuery("#messages").html('<p class="save_error">Error while saving your note.</p><p class="save_error">Please try submitting again.</p><p class="save_error">If error continues please contact support.</p><p>Error: ' + textStatus + ", " + errorThrown+'</p>');
	
	// Send error details in a support email
	jQuery("#note input").removeAttr("disabled");	
	jQuery("#note input[name=submit]").show();	
}

function ajaxOnSuccess(data) {
	jQuery("#note input").removeAttr("disabled");
	
	if ('0' != data.status) {
	  jQuery("#messages").html('<p class="warning">'+data.messages.join(".")+'</p>').fadeOut(2000);

	  if (null != data.feedback.note) {
	    jQuery("#noteFeedback").html(data.feedback.note).show();
	  }
	  
	  if (null != data.feedback.username) {
		jQuery("#usernameFeedback").html(data.feedback.username).show();
	  }	 
	  
	  if (null != data.feedback.page_id) {
			jQuery("#pageIDFeedback").html(data.feedback.page_id).show();
	  }		  
	} else {	
	  jQuery("#messages").html('<p class="saveSuccess">Your data has been saved</p>').fadeOut('slow').fadeIn('slow').fadeOut('slow');
	  appendNote();
	}	
	
	jQuery("#messages").show();
	jQuery('#noteContent').attr('value', '').focus();
}

function appendNote() {
	var currentTime = new Date();
	var time = formatLeadingZero(currentTime.getHours())+":"+formatLeadingZero(currentTime.getMinutes())+":"+formatLeadingZero(currentTime.getSeconds());
	var date = currentTime.getFullYear()+"/"+(currentTime.getMonth() + 1)+"/"+currentTime.getDate()+" "+time;

	var html = "<tr class=\"header\"> \
        <th>"+jQuery('#username').val()+"</th> \
        <th>"+date+"</th> \
      </tr> \
      <tr id=\"justAdded\" class=\"even\"> \
        <td colspan=\"2\">"+jQuery('#noteContent').val()+"</td> \
      </tr>";

    jQuery("#noteList").prepend(html.nl2br());
    jQuery('#justAdded').fadeOut('slow').fadeIn('slow').fadeOut('slow').fadeIn('slow');
}

function formatLeadingZero(number) {
	var number  = number * 1;
	var leading = number < 10 ? '0' : '';
	return (leading + number);
}

String.prototype.nl2br = function() {
	var br;
	if (typeof arguments[0] != 'undefined') {
		br = arguments[0];
	} else {
		br = '<br />';
	}
	
	return this.replace(/\r\n|\r|\n/g, br);
};
 
String.prototype.br2nl = function() {
	var nl;
	if( typeof arguments[0] != 'undefined' ) {
		nl = arguments[0];
	} else {
		nl = '\r\n';
	}
	return this.replace( /\<br(\s*\/|)\>/g, nl);
};